package com.hctforgreen.greenservice.ui.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.TechnicalDataActivityV4;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookClickListEntity;
import com.hctforgreen.greenservice.model.BookClickListEntity.BookClickEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.ColumnListEntity.ColumnEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.Md5Util;

/**
 * 从"调试维修"进入的栏目列表
 * 
 * @author Tallen Zhai
 * 
 */
public class DebugBooksColumnListAdapter extends BaseAdapter implements
		OnItemClickListener {

	private Activity mActivity;
	private View mConvertView;
	private ListView mListView;
	private ArrayList<ColumnEntity> mEntities;

	private MachineEntity mMachineEntity;

	public DebugBooksColumnListAdapter(Activity activity, View convertView,
			ListView listView, ArrayList<ColumnEntity> entities,
			final MachineEntity entity,
			final BookClickListEntity clickListEntity) {
		mActivity = activity;
		mConvertView = convertView;
		mListView = listView;

		mEntities = entities;
		mMachineEntity = entity;
		sortBookList(mEntities, clickListEntity);
		mListView.setAdapter(this);
		mListView.setOnItemClickListener(this);
	}

	private static Comparator<BookEntity> comparator = new Comparator<BookEntity>() {
		public int compare(BookEntity entity1, BookEntity entity2) {

			if (Integer.valueOf(entity1.clickCount) < Integer
					.valueOf(entity2.clickCount)) {
				return 1;
			} else if (Integer.valueOf(entity1.clickCount) == Integer
					.valueOf(entity2.clickCount)) {
				/**
				 * 不交换位置
				 */
				return 0;
			} else {
				return -1;
			}

		}
	};

	private void sortBookList(ArrayList<ColumnEntity> entities,
			final BookClickListEntity clickListEntity) {
		if (clickListEntity == null || clickListEntity.dataList == null
				|| clickListEntity.dataList.size() == 0) {
			return;
		}
		for (ColumnEntity cEntity : entities) {
			if (cEntity.dataList != null && cEntity.dataList.size() > 0) {
				for (BookEntity bEntity : cEntity.dataList) {
					for (BookClickEntity clickEntity : clickListEntity.dataList) {
						if (bEntity.id.equals(clickEntity.bookId)) {
							bEntity.clickCount = clickEntity.clickCount;
						}
					}
				}

				Collections.sort(cEntity.dataList, comparator);
			}

		}

	}

	@Override
	public int getCount() {
		return mEntities.size();
	}

	@Override
	public Object getItem(int position) {
		return mEntities.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewCache viewCache;
		final ColumnEntity entity = (ColumnEntity) getItem(position);
		if (convertView == null) {
			convertView = View.inflate(mActivity,
					R.layout.item_debug_book_column_lst, null);
			viewCache = new ViewCache(convertView);
			convertView.setTag(viewCache);
		} else {
			viewCache = (ViewCache) convertView.getTag();
		}
		viewCache.getNameTv().setText(entity.name);

		initOffRb(viewCache, entity);

		initIconIv(viewCache, entity, position);

		initChildContainerLayout(viewCache, entity.dataList);

		viewCache.getColumnLyt().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (position == mEntities.size() - 1) {

					loadSerieEntityAndChildSerieEntity(v,
							viewCache.getLoadingPb());
					return;
				}
				if (entity.isOff) {
					for (ColumnEntity bean : mEntities) {
						bean.isOff = true;
					}
					entity.isOff = false;
					notifyDataSetChanged();
					if (!entity.isOff) {
						mListView.setSelection(position);
					}
				} else if (!entity.isOff) {
					entity.isOff = !entity.isOff;
					notifyDataSetChanged();
				}
			}
		});
		return convertView;
	}

	private void loadSerieEntityAndChildSerieEntity(final View v,
			final ProgressBar loadingPb) {

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadingPb.setVisibility(View.GONE);
					v.setClickable(true);

					hctResult = (HctResult) msg.obj;

					SerieEntity serieEntity = (SerieEntity) hctResult.data;

					ChildSerieEntity childSerieEntity = initChildSerieEntity(serieEntity);

					startTechDataActivity(serieEntity, childSerieEntity);
					break;

				case HctConstants.STATUS_FAILD:
					loadingPb.setVisibility(View.GONE);
					v.setClickable(true);
					break;
				}
			}

			private ChildSerieEntity initChildSerieEntity(
					SerieEntity serieEntity) {
				ChildSerieEntity childSerieEntity = null;
				if (serieEntity == null || serieEntity.childList == null) {
					return null;
				}
				for (ChildSerieEntity cEntity : serieEntity.childList) {
					if (mMachineEntity.childSeriesId
							.equals(cEntity.childSeriesId)) {
						childSerieEntity = cEntity;
					}
				}
				return childSerieEntity;
			}

			@Deprecated
			private SerieEntity initDefaultSerieEntity(
					List<SerieEntity> dataList) {
				SerieEntity serieEntity = null;

				for (SerieEntity sEntity : dataList) {
					if (mMachineEntity.seriesId.equals(sEntity.id)) {
						serieEntity = sEntity;

					}
				}
				return serieEntity;
			}

			private void startTechDataActivity(SerieEntity serieEntity,
					ChildSerieEntity childSerieEntity) {
				Intent intent = new Intent();
				intent.setClass(mActivity, TechnicalDataActivityV4.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
						mMachineEntity);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_SERIES_ENTITY,
						serieEntity);
				intent.putExtra(
						HctConstants.ON_ACTIVITY_KEY_CHILD_SERIE_ENTITY,
						childSerieEntity);
				mActivity.startActivity(intent);
			}

		};
		v.setClickable(false);
		loadingPb.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller
							.getDbSingleSeriesWithDbChildSeries(mMachineEntity.seriesId);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void initChildContainerLayout(ViewCache viewCache,
			final List<BookEntity> childEntities) {

		if (viewCache.getChildContainerLyt().getChildCount() == 0) {
			if (childEntities == null) {
				return;
			}
			for (int i = 0; i < childEntities.size(); i++) {
				final LinearLayout childLyt = (LinearLayout) mActivity
						.getLayoutInflater()
						.inflate(R.layout.item_debug_book_column_child_lst,
								null);

				final BookEntity entity = childEntities.get(i);
				childLyt.setId(i);

				TextView nameTv = (TextView) childLyt
						.findViewById(R.id.tv_name);
				nameTv.setText(entity.displayName);

				childLyt.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
						try {
							catalogUtil.startEntryCatalogActivity(mActivity,
									entity, true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				viewCache.getChildContainerLyt().addView(childLyt, i);

			}
		}

	}

	private void initOffRb(ViewCache viewCache, final ColumnEntity entity) {
		if (entity.dataList == null) {
			viewCache.getOffIv().setVisibility(View.INVISIBLE);
			return;
		}
		viewCache.getOffIv().setVisibility(View.VISIBLE);
		if (entity.isOff) {
			viewCache.getChildContainerLyt().setVisibility(View.GONE);
			viewCache.getOffIv().setImageResource(R.drawable.ic_off_normal);
		} else if (!entity.isOff) {
			viewCache.getChildContainerLyt().setVisibility(View.VISIBLE);
			viewCache.getOffIv().setImageResource(R.drawable.ic_on_normal);
		}
	}

	private void initIconIv(ViewCache viewCache, final ColumnEntity entity,
			final int position) {
		if (position == mEntities.size() - 1) {
			viewCache.getIconIv().setImageResource(
					R.drawable.ic_default_book_icon);
			return;
		}
		viewCache.getIconIv().setTag(Md5Util.md5(entity.icon));
		AsyncImageLoader imageLoader = new AsyncImageLoader();
		Drawable cacheDrawable = imageLoader.loadDrawable(entity.icon,
				mActivity, true, new ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						ImageView tagImage = (ImageView) mListView
								.findViewWithTag(imageUrl);
						if (tagImage != null) {
							if (imageDrawable != null) {
								tagImage.setImageDrawable(imageDrawable);
							} else {
								// tagImage.setImageResource(R.drawable.ic_default_pic);
							}
						}

					}
				});
		if (cacheDrawable != null) {
			viewCache.getIconIv().setImageDrawable(cacheDrawable);
		} else {
			// viewCache.getIconIv().setImageResource(R.drawable.ic_default_pic);
		}
	}

	class ViewCache {
		private View baseView;

		private TextView nameTv;
		private ImageView iconIv;
		private ImageView offIv;
		private LinearLayout parentLyt;
		private LinearLayout childLyt;
		private ProgressBar loadingPb;

		public ViewCache(View view) {
			baseView = view;
		}

		public TextView getNameTv() {
			if (nameTv == null) {
				nameTv = (TextView) baseView.findViewById(R.id.tv_column_name);
			}
			return nameTv;
		}

		public ImageView getIconIv() {
			if (iconIv == null) {
				iconIv = (ImageView) baseView.findViewById(R.id.iv_column_icon);
			}
			return iconIv;
		}

		public ImageView getOffIv() {
			if (offIv == null) {
				offIv = (ImageView) baseView.findViewById(R.id.iv_off);
			}
			return offIv;
		}

		public LinearLayout getColumnLyt() {
			if (parentLyt == null) {
				parentLyt = (LinearLayout) baseView
						.findViewById(R.id.lyt_column);
			}
			return parentLyt;
		}

		public LinearLayout getChildContainerLyt() {
			if (childLyt == null) {
				childLyt = (LinearLayout) baseView
						.findViewById(R.id.lyt_child_container);
			}
			return childLyt;
		}

		public ProgressBar getLoadingPb() {
			if (loadingPb == null) {
				loadingPb = (ProgressBar) baseView
						.findViewById(R.id.pb_loading);
			}
			return loadingPb;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

	}

}
